package com.vvkee.customer;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;

import java.util.List;
import java.util.Map;
import java.util.Set;

public class VvkeeApplicationContext {

    // 单例池，储存单例Bean
    private Map<String, Object> singleObjects = Maps.newHashMap();

    // 事件广播器
    private static final String APPLICATION_EVENT_MULTICASTER_BEAN_NAME = "applicationEventMulticaster";
    private VvkeeApplicationEventMulticaster applicationEventMulticaster;

    // 存储所有等待Spring创建的Bean的名字
    private volatile List<String> beanDefinitionNames = Lists.newArrayList();

    // 存储所有的监听器
    private final Set<VvkeeApplicationListener<?>> applicationListeners = Sets.newLinkedHashSet();

    public VvkeeApplicationContext() {
        register();
        refresh();
    }

    public void register() {
        beanDefinitionNames.add("");
    }

    public void refresh() {
        // 初始化事件广播器
        initApplicationEventMulticaster();
        //
        finishBeanFactoryInitialization();
    }

    public void initApplicationEventMulticaster() {
        if (beanDefinitionNames.contains(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
            applicationEventMulticaster = (VvkeeApplicationEventMulticaster) singleObjects.get(APPLICATION_EVENT_MULTICASTER_BEAN_NAME);
        } else {
            // applicationEventMulticaster = new VvkeeSimpleApplicationEventMulticaster();
        }
    }

    private void finishBeanFactoryInitialization() {
        for (String beanName : beanDefinitionNames) {
            doCreateBean(beanName);
        }
    }

    private void doCreateBean(String beanName) {
        Object bean = null;
        try {
            // 反射创建Bean
            bean = createBeanInstance(beanName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 初始化
        initializeBean(bean);
        // 存入单例池
       //  singletonObjects.put(beanName, bean);
    }

    /**
     * 反射创建Bean实例（空实例）
     * @param beanName
     * @return
     * @throws Exception
     */
    public Object createBeanInstance(String beanName) throws Exception {
        return Class.forName(beanName).newInstance();
    }

    /**
     * 初始化Bean
     * @param bean
     */
    public void initializeBean(Object bean) {
        // 如果当前Bean实现了事件监听接口，则加入广播器
        // applyBeanPostProcessorsAfterInitialization(bean);
    }


}
